import { createRouter, createWebHashHistory } from 'vue-router'
import { useAuthStore } from '../store/auth'

const routes = [
  {
    path: '/',
    redirect: '/dashboard'
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import('../views/Login.vue')
  },
  {
    path: '/dashboard',
    name: 'Dashboard',
    component: () => import('../views/Dashboard.vue'),
    meta: { requiresAuth: true }
  },
  {
    path: '/scripts',
    name: 'Scripts',
    component: () => import('../views/Scripts.vue'),
    meta: { requiresAuth: true }
  },
  {
    path: '/execution-logs',
    name: 'ExecutionLogs',
    component: () => import('../views/ExecutionLogs.vue'),
    meta: { requiresAuth: true }
  }
]

const router = createRouter({
  history: createWebHashHistory(),
  routes
})

router.beforeEach(async (to, from, next) => {
  console.log(`路由守卫: 从 ${from.path} 到 ${to.path}`)
  
  const authStore = useAuthStore()
  
  // 检查是否需要认证
  if (to.meta.requiresAuth) {
    console.log('目标页面需要认证')
    
    // 检查认证状态
    const isAuthenticated = authStore.isAuthenticated
    console.log('当前认证状态:', isAuthenticated)
    
    if (isAuthenticated) {
      // 已认证，允许访问
      console.log('用户已认证，允许访问')
      next()
    } else {
      // 未认证，尝试检查认证状态
      console.log('用户未认证，尝试检查认证状态...')
      const isValid = await authStore.checkAuth()
      
      if (isValid) {
        console.log('认证检查成功，允许访问')
        next()
      } else {
        console.log('认证检查失败，跳转到登录页')
        next('/login')
      }
    }
  } else {
    // 不需要认证的页面，直接允许访问
    console.log('目标页面不需要认证，允许访问')
    next()
  }
})

export default router
